﻿#if WINDOWS_PHONE
#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/
#endregion

using System.Windows;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

using Outcoder.ComponentModel;

namespace Outcoder.Services.Implementation
{
	public partial class LockScreenService
	{
		void InitializeWhenReady()
		{
			if (!(Application.Current.RootVisual is PhoneApplicationFrame))
			{
				/* This is invoked in case this call is made before the RootVisual has been assigned. */
				Deployment.Current.Dispatcher.BeginInvoke(InitializeCore);
			}
			else
			{
				InitializeCore();
			}
		}

		void InitializeCore()
		{
			var settingsService = Dependency.Resolve<ISettingsService, SettingsService>();

			if (settingsService.ContainsSetting(promptedKey))
			{
				UserPrompted = true;
			}

			RunningUnderLockScreenEnabled = settingsService.GetSetting(runningEnabledKey, false);

			var frame = (PhoneApplicationFrame)Application.Current.RootVisual;
			frame.Obscured += HandleFrameObscured;
			frame.Unobscured += HandleFrameUnobscured;
		}

		void HandleFrameObscured(object o, ObscuredEventArgs args)
		{
			RunningUnderLockScreen = args.IsLocked;

			IMessenger messenger;
			if (Dependency.TryResolve<IMessenger>(out messenger))
			{
				messenger.Publish(new LockScreenEvent(LockScreenEvent.LockScreenState.Engaged));
			}
		}

		void EnableRunningUnderLockScreen()
		{
			PhoneApplicationService.Current.ApplicationIdleDetectionMode
															= IdleDetectionMode.Disabled;
		}
	}
}
#endif